package com.fly.show.csdn.service.init.impl;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.fly.core.utils.JsonBeanUtils;
import com.fly.show.csdn.entity.Article;
import com.fly.show.csdn.entity.BlogData;
import com.fly.show.csdn.service.init.DataInitor;

import lombok.extern.slf4j.Slf4j;

/**
 * 通过资源文件初始化
 */
@Slf4j
@Order(3)
@Component
public class ResourceDataInitor implements DataInitor
{
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    
    @Override
    public boolean init(List<Article> articles)
    {
        try
        {
            log.info("start init...");
            Resource[] jsons = resolver.getResources("classpath:*.json");
            articles.addAll(Arrays.stream(jsons).map(json -> parseToArticles(json)).flatMap(List::stream).distinct().collect(Collectors.toList()));
            return !CollectionUtils.isEmpty(articles);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 解析Resource为List
     * 
     * @param resource
     * @return
     */
    private List<Article> parseToArticles(Resource resource)
    {
        try (InputStream input = resource.getInputStream())
        {
            String jsonData = IOUtils.toString(input, StandardCharsets.UTF_8);
            return JsonBeanUtils.jsonToBean(jsonData, BlogData.class, true).getData().getList();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}